import { getCommentsByIdAPI } from '@/api/article';
import {
  dislikeCommentByIdAPI,
  ICommentParams,
  likeCommentByIdAPI,
  sendCommentAPI,
} from '@/api/comment';
import { Toast } from 'antd-mobile';
import store, { AppDispatch } from '..';
import { ActionType, ICommentItem } from '../reducer/comment';

export const getCommentsByIdAction = (id: string, type: 'a' | 'c') => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI(id, type);
    dispatch({ type: 'comment/saveComments', payload: res.data });
  };
};

export const clearCommentsAction = (): ActionType => ({
  type: 'comment/saveComments',
  payload: {} as any,
});

export const saveOriginAction = (commemt: ICommentItem): ActionType => ({
  type: 'comment/saveOriginComment',
  payload: commemt,
});

export const clearOriginAction = (): ActionType => ({
  type: 'comment/clearOriginComment',
});

export const sendCommentAction = (data: ICommentParams) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { com_id } = getState().comment.originComment;
    const { art_id } = getState().article.detail;
    if (!com_id) {
      const res = await sendCommentAPI(data);
      dispatch({ type: 'comment/updateComments', payload: res.data.new_obj });
    } else {
      const res = await sendCommentAPI({ content: data.content, target: com_id, art_id });
      console.log('res  ----->  ', res);
    }
  };
};

export const getReplyCommentsAction = (id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI(id, 'c');
    dispatch({ type: 'comment/saveReplyComment', payload: res.data });
  };
};

export const clearReplyCommentAction = (): ActionType => ({
  type: 'comment/clearReplyComment',
});

export const likeCommentByIdActon = (
  id: string,
  isLiking: boolean,
  type?: 'normal' | 'reply' | 'origin'
) => {
  return async (dispatch: any, getState: typeof store.getState) => {
    const { originComment } = getState().comment;
    const { detail } = getState().article;
    if (isLiking) {
      await dislikeCommentByIdAPI(id);
    } else {
      await likeCommentByIdAPI(id);
    }

    Toast.show({ content: isLiking ? '取消点赞' : '点赞成功' });

    if (type === 'origin') {
      dispatch(getCommentsByIdAction(detail.art_id, 'a'));
      return;
    }

    if (type === 'reply') {
      dispatch(getReplyCommentsAction(originComment.com_id));
      return;
    }

    if (type === 'normal') {
      dispatch(getCommentsByIdAction(detail.art_id, 'a'));
    }
  };
};
